package com.lx.web;

import com.lx.entity.Admin;
import com.lx.entity.User;
import com.lx.service.AdminService;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class AdminServlet {
    @Autowired
    private AdminService adminService;

    //跳转到管理员登录成功页面
    @RequestMapping("/toSystem")
    public String system(){
        return "/WEB-INF/jsp/system.jsp";
    }

    //跳转到管理员登陆页面
    @RequestMapping("/toAdminLogin")
    public String toAdminLogin(){
        return "/WEB-INF/jsp/logins.jsp";
    }

    //管理员登陆
    @RequestMapping("/adminLogin")
    public String adminLogin(String name, String password, HttpSession session){
        Admin admin = adminService.adminLogin(name, password);
        if (admin == null){
            return "redirect:/toAdminLogin";
        }else {
            session.setAttribute("admin",admin);
            return "redirect:/toSystem";
        }
    }

    //跳转到注册管理员页面
    @RequestMapping("/toAdminRegister")
    public String toAdminRegister(){
        return "/WEB-INF/jsp/adminRegister.jsp";
    }

    //注册管理员
    @RequestMapping("/adminRegister")
    public String adminRegister(String name,String password){
        Admin admin = adminService.adminRegister(name, password);
        if (admin == null){
            return "redirect:/toAdminRegister";
        }else {
            return "redirect:/toAdmin";
        }
    }

    //退出登录
    @RequestMapping("/logoutAdmin")
    public String logout(HttpServletRequest request){
        request.getSession().invalidate();
        return "redirect:/toAdminLogin";
    }

    //查询所有用户
    @RequestMapping("/userList")
    public String userList(String page,HttpServletRequest request){
        int p = 1; //默认显示第一页
        if (page != null && !"".equals(page)) {
            //特殊字符无法转换，捕获
            try {
                p = Integer.parseInt(page);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
        List<User> users = adminService.getUser(p, 4);
        int count = adminService.countUser();
        int n = count % 4 ==0 ? count / 4 :count / 4 +1;
        request.setAttribute("pageNumber",n);
        request.setAttribute("page",p);
        request.setAttribute("users",users);
        return "/WEB-INF/jsp/userList.jsp";
    }
}
